import types

import bson

bson_encode = bson.BSON.encode

class Collection(object):
    def __init__(self, conn, cs_name, c_name):
        self._conn = conn
        self._cs_name = cs_name
        self._c_name = c_name

    def __str__(self):
        return 'Collection(name=%s.%s)' % (self._cs_name, self._c_name)
    
    def insert(self, record):
        assert type(record) is types.DictType
        bytes_record = bson.BSON.encode(record)
        id_str = self._conn.insert(self._cs_name, self._c_name, bytes_record)
        return bson.ObjectId(id_str)

    def bulk_insert(self, flag, records):
        bytes_records = []
        for record in records:
            assert type(record) is types.DictType
            bytes_records.append(bson.BSON.encode(record))
        return self._conn.bulk_insert(self._cs_name, self._c_name, flag, bytes_records)

    def query(self, **kw):
        bson_condition = kw.get('condition')
        if bson_condition:
            bson_condition = bson_encode(bson_condition)

        bson_selector = kw.get('selector')
        if bson_selector:
            bson_selector = bson_encode(bson_selector)

        bson_order_by = kw.get('order_by')
        if bson_order_by:
            bson_order_by = bson_encode(bson_order_by)

        bson_hint = kw.get('hint')
        if bson_hint:
            bson_hint = bson_encode(bson_hint)

        num_to_skip = kw.get('num_to_skip', 0L)
        num_to_return = kw.get('num_to_return', -1L)

        return self._conn.query(self._cs_name,
            self._c_name,
            bson_condition,
            bson_selector,
            bson_order_by,
            bson_hint,
            num_to_skip,
            num_to_return)

